<template>
  <div class="login">
    <section class="form_container">
      <div class="manage_tip">
        <span class="title">校园点餐管理平台</span>
      </div>
      <el-form
        :model="loginUser"
        :rules="rules"
        ref="loginForm"
        class="loginForm"
        label-width="80px"
      >
        <el-form-item label="身份证号" prop="number">
          <el-input v-model="loginUser.number" placeholder="请输入身份证号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginUser.password" placeholder="请输入密码" type="password"></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input
            type="text"
            id="code"
            size="mini"
            v-model="code"
            class="code"
            placeholder="请输入验证码"
          />
          <div class="login-code" @click="refreshCode" style="float: left;">
            <!--验证码组件-->
            <s-identify :identifyCode="identifyCode"></s-identify>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="submitForm('loginForm')" class="submit_btn">登 录</el-button>
        </el-form-item>
        <div class="tiparea">
          <i class="regisetr">
            还没有账号？现在
            <router-link to="/register">注册</router-link>
          </i>
           <i class="forgetPass">
            忘记密码？
            <router-link to="/forgetPass">找回</router-link>
          </i>
        </div>
      </el-form>
    </section>
  </div>
</template>

<script>
import jwt_decode from "jwt-decode";
import SIdentify from "./component/sidentify";
export default {
  name: "login",
  components: {
    SIdentify
  },
  data() {
    return {
      loginUser: {
        number: "",
        password: ""
      },
      identifyCodes: "1234567890",
      identifyCode: "",
      code: "", //text框输入的验证码
      rules: {
        number: [
          {
            required: true,
            message: "身份证号不能为空",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 30, message: "长度在 6 到 30 个字符", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.refreshCode();
  },
  mounted() {
    this.identifyCode = "";
    this.makeCode(this.identifyCodes, 4);
  },
  methods: {
    submitForm(formName) {
      if (this.code == "") {
        return this.$message.warning("请输入验证码");
      }
      if (this.identifyCode !== this.code) {
        this.code = "";
        this.refreshCode();
        return this.$message.error("请输入正确的验证码");
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$api.post("/api/users/login", this.loginUser).then(res => {
            // 登录成功
            const { token } = res.data;
            localStorage.setItem("eleToken", token);
            // 解析token
            const decode = jwt_decode(token);
            // 判断是否是普通学生
            if (decode.role === "student") {
              return this.$message.error("您是普通学生，无权访问后台管理系统");
            }
            this.$api
              .get("/api/user/list", { params: { number: decode.number } })
              .then(res => {
                this.$store.dispatch(
                  "setIsAutnenticated",
                  !this.isEmpty(decode)
                );
                this.$store.dispatch("setUser", res.data.data.records[0]);
              }).catch(res=>{
                this.$message.error("失败！");
              })

            // 页面跳转
            this.$router.push("/");
          });
        } else {
          return false;
        }
      });
    },
    isEmpty(value) {
      return (
        value === undefined ||
        value === null ||
        (typeof value === "object" && Object.keys(value).length === 0) ||
        (typeof value === "string" && value.trim().length === 0)
      );
    },
    refreshCode() {
      this.identifyCode = "";
      console.log(this.identifyCodes);
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      console.log(this.identifyCode, this.identifyCodes);
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
          this.randomNum(0, this.identifyCodes.length)
        ];
      }
      console.log(this.identifyCode);
    },
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    }
  }
};
</script>

<style scoped>
.login {
  position: relative;
  width: 100%;
  height: 100%;
  background: url(../../assets/bg.jpg) no-repeat center center;
  background-size: 100% 100%;
}
.form_container {
  width: 450px;
  height: 360px;
  background-color: rgba(255,255,255,.6);
  position: absolute;
   left:50%;
    top:50%;
    transform: translate(-50%, -50%);
  padding: 20px;
  border-radius: 5px;
  text-align: center;
}
.form_container .manage_tip .title {
  font-family: "Microsoft YaHei";
  font-weight: bold;
  font-size: 26px;
  color: #000;
}
.loginForm {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px 40px 20px 20px;
  border-radius: 5px;
  box-shadow: 0px 5px 10px #cccc;
}

.submit_btn {
  width: 100%;
}
.tiparea {
  font-size: 12px;
  color: #333;
}
.tiparea .regisetr a {
 margin-right:70px;
  color: #409eff;
}
.tiparea .forgetPass a {
      color:#409eff;
}
.code {
  width: 110px;
  height: 31px;
}
.login-code {
  cursor: pointer;
}
</style>


